/*
 * @(#) PartInterService.java 2013-8-6 下午1:22:14
 *
 * Copyright 2013 Rockwell Automation, Inc. All rights reserved.
 * Rockwell Automation PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */package com.osi.mes.inter.erp;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

import pnuts.lang.Context;
import com.datasweep.compatibility.client.ATHandler;
import com.datasweep.compatibility.client.ATRow;
import com.datasweep.compatibility.client.ATRowFilter;
import com.datasweep.compatibility.client.Response;
import com.datasweep.compatibility.pnuts.Functions;
import com.osi.mes.inter.BaseInterService;
import com.osi.mes.pm.PMService;
import com.rockwell.ftpc.framework.common.XMLUtils;
import com.rockwell.ftpc.framework.common.XmlData;
import com.rockwell.ftpc.framework.exception.MESException;
import com.rockwell.mes.rtmis.middle.constants.IMDConstants;
import com.rockwell.mes.rtmis.middle.objects.ResponseObject;
import com.rockwell.mes.rtmis.middle.utils.MDUtils;
import com.rockwell.transactiongrouping.UserTransaction;

public class BusinessPartnerInterService extends BaseInterService
{

	private static BusinessPartnerInterService instatnce = null;

	private static PMService pmService = null;

	private BusinessPartnerInterService(Context context)
	{
		super(context);
	}

	private BusinessPartnerInterService(Functions functions)
	{
		super(functions);
	}

	public static BusinessPartnerInterService getInstance(Context context)
	{
		if (instatnce == null)
		{
			synchronized (BusinessPartnerInterService.class)
			{
				if (instatnce == null)
				{
					instatnce = new BusinessPartnerInterService(context);
					pmService = new PMService(context);
				}
			}
		}
		return instatnce;
	}

	public Hashtable<String, Object> receiveBusinessPartner(Hashtable receivedData)
	{
		UserTransaction ut = null;
		Hashtable<String, Object> returnValue = new Hashtable<String, Object>();
		try
		{
			Response r = getFunctions().getUserTransaction();
			ut = (UserTransaction) r.getResult();
			ut.setTransactionTimeout(120);
			ut.begin();
			String msgObjType = (String) receivedData.get(IMDConstants.MD_TABLE_COULMN_MSGObJ_TYPE);
			if (!"2".equals(msgObjType))
			{
				throw new Exception(
					"The MSGObjType value does not matched, it should be 2 instead of "
						+ msgObjType);
			}
			String msgTransType = (String) receivedData
				.get(IMDConstants.MD_TABLE_COULMN_MSG_TRANS_TYPE);

			// String msgKeyFields =
			// receivedData.get(IMDConstants.MD_TABLE_COULMN_MSG_KEY_FIELDS);
			String msgFieldsValue = (String) receivedData
				.get(IMDConstants.MD_TABLE_COULMN_MSG_FIELDS_VALUE);
			String msgContent = (String) receivedData.get(IMDConstants.MD_TABLE_COULMN_MSG_CONTENT);
			XmlData xmlData = XMLUtils.strToXMLData(msgContent);
			Hashtable<String, ArrayList<Object>> value = xmlData.getData();

			ATRowFilter atRowFilter = getFunctions().createATRowFilter(
				AT_TABLE_NAME_BUSINESS_PARTNER);
			atRowFilter.forColumnNameEqualTo(
				AT_COLUMN_NAME_BUSINESS_PARTNER_CODE, msgFieldsValue);
			ATHandler atHandler = getFunctions().createATHandler(
				AT_TABLE_NAME_BUSINESS_PARTNER);

			if (INTER_STR_CREATE.equalsIgnoreCase(msgTransType))
			{
				int atRowCount = getFunctions().getFilteredATRowCount(
					atRowFilter);
				if (atRowCount > 0)
				{
					throw new Exception(
						"The business partner object has already existed in RTMIS, the CardCode is "
							+ msgFieldsValue);
				}
				ATRow atRow = atHandler.createATRow();
				atRow.setValue(
					UDA_INTER_FLAG_SAP, INTER_CREATE);
				saveHashtableToBusinessPartnerObject(
					atRow, value);
			}
			else if (INTER_STR_UPDATE.equalsIgnoreCase(msgTransType))
			{
				Vector atRows = atHandler.getATRowsByFilter(
					atRowFilter, false);
				if (atRows == null || atRows.size() == 0)
				{
					throw new Exception(
						"The business partner object did not exist in RTMIS, the CardCode is "
							+ msgFieldsValue);
				}
				ATRow atRow = (ATRow) atRows.get(0);
				atRow.setValue(
					UDA_INTER_FLAG_SAP, INTER_UPDATE);
				saveHashtableToBusinessPartnerObject(
					atRow, value);
			}
			else if (INTER_STR_DELETE.equalsIgnoreCase(msgTransType))
			{
				Vector atRows = atHandler.getATRowsByFilter(
					atRowFilter, false);
				if (atRows == null || atRows.size() == 0)
				{
					throw new Exception(
						"The business partner object did not exist in RTMIS, the CardCode is "
							+ msgFieldsValue);
				}
				ATRow atRow = (ATRow) atRows.get(0);
				atRow.setValue(
					UDA_INTER_FLAG_SAP, INTER_DELETE);
				Response response = atRow.save(
					getFunctions().getDBTime(), null, null);
				if (response.isError())
				{
					throw new Exception(response.getFirstErrorMessage());
				}
			}
			sendBusinessPartnersToWMS(receivedData);
			returnValue.put(
				IMDConstants.RESPONSE_STATUS, IMDConstants.RESPONSE_STATUS_SUCCESSFUL);
			ut.commit();
		}
		catch (Exception e)
		{
			returnValue.put(
				IMDConstants.RESPONSE_STATUS, IMDConstants.RESPONSE_STATUS_FAILED);
			returnValue.put(
				IMDConstants.RESPONSE_LAST_ERR_MSG, e.getMessage());
			ut.rollback();

		}
		return returnValue;
	}

	private void saveHashtableToBusinessPartnerObject(ATRow atRow,
		Hashtable<String, ArrayList<Object>> value)
		throws Exception
	{
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CODE, getTransferValue(
				value, "CardCode"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_NAME, getTransferValue(
				value, "CardName"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_TYPE, getTransferValue(
				value, "CardType"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CLASS1, getTransferValue(
				value, "Class1"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CLASS2, getTransferValue(
				value, "Class2"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CLASS3, getTransferValue(
				value, "Class3"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CLASS4, getTransferValue(
				value, "Class4"));
		atRow.setValue(
			AT_COLUMN_NAME_BUSINESS_PARTNER_CLASS5, getTransferValue(
				value, "Class5"));
		Response response = atRow.save(
			getFunctions().getDBTime(), null, null);
		if (response.isError())
		{
			throw new Exception(response.getFirstErrorMessage());
		}
	}

	/**
	 * 将业务伙伴主数据发送给WMS
	 * 
	 * @param parts
	 *            物料主数据
	 * @param method
	 *            0:新建 1：更新 2：删除
	 */
	public void sendBusinessPartnersToWMS(Hashtable receivedData)
		throws MESException
	{
		try
		{
			String xmlStr = XMLUtils.toXMLStr(receivedData);
			xmlStr = xmlStr.replaceAll(
				"<xml>", "<MiddleToWMS>");
			xmlStr = xmlStr.replaceAll(
				"</xml>", "</MiddleToWMS>");
			System.out.println(xmlStr);
			String result = MDUtils.invokeDNetWebService(
				"http://10.108.147.228/wmsmesservice.asmx", "http://tempuri.org/",
				"MiddlewareToWMS", "http://tempuri.org/MiddlewareToWMS", "content", xmlStr);
			System.out.println(result);
			XmlData xmlData = XMLUtils.strToXMLData(result);
			Hashtable<String, ArrayList<Object>> data = xmlData.getData();
			ResponseObject responseObject = MDUtils.hashtableToResponseObject(data);
			int status = responseObject.getStatus();
			if (status == 1)
			{
				throwException("发送业务伙伴主数据确认到WMS失败,原因为" + responseObject.getLastErrMsg());
			}
		}
		catch (Exception e)
		{
			throw new MESException(e, MODULE_IM, "发送业务伙伴主数据到WMS");
		}
	}

}
